#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
批量修复所有Django导入问题
"""
import os
import re

def fix_file_imports(file_path):
    """修复单个文件的导入问题"""
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        original_content = content
        
        # 1. 修复 django.core.urlresolvers 导入
        content = re.sub(
            r'from django\.core\.urlresolvers import',
            'from django.urls import',
            content
        )
        
        # 2. 修复 ugettext_lazy 导入
        content = re.sub(
            r'from django\.utils\.translation import ([^,]*,\s*)?ugettext_lazy as _',
            r'from django.utils.translation import \1gettext_lazy as _',
            content
        )
        
        # 3. 修复 ugettext 导入
        content = re.sub(
            r'from django\.utils\.translation import ([^,]*,\s*)?ugettext,',
            r'from django.utils.translation import \1gettext as ugettext,',
            content
        )
        
        # 4. 修复 Django 1.6+ 简单JSON导入
        content = re.sub(
            r'from django\.utils\.simplejson',
            'import json #',
            content
        )
        
        # 5. 修复 force_unicode
        content = re.sub(
            r'from django\.utils\.encoding import ([^,]*,\s*)?force_unicode',
            r'from django.utils.encoding import \1force_text as force_unicode',
            content
        )
        
        # 6. 修复 smart_unicode
        content = re.sub(
            r'from django\.utils\.encoding import ([^,]*,\s*)?smart_unicode',
            r'from django.utils.encoding import \1smart_text as smart_unicode',
            content
        )
        
        # 只有在内容发生变化时才写入文件
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"✓ 修复: {file_path}")
            return True
        return False
            
    except Exception as e:
        print(f"✗ 错误 {file_path}: {e}")
        return False

def main():
    """主函数"""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    
    print("批量修复Django导入问题...")
    print("=" * 40)
    
    # 获取所有Python文件
    python_files = []
    for root, dirs, files in os.walk(base_dir):
        # 跳过某些目录
        dirs[:] = [d for d in dirs if d not in ['__pycache__', '.git']]
        
        for file in files:
            if file.endswith('.py'):
                python_files.append(os.path.join(root, file))
    
    print(f"找到 {len(python_files)} 个Python文件")
    
    # 修复文件
    fixed_count = 0
    
    for file_path in python_files:
        if fix_file_imports(file_path):
            fixed_count += 1
    
    print("=" * 40)
    print(f"修复完成！成功修复 {fixed_count} 个文件")

if __name__ == '__main__':
    main() 